package com.Serverce;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.Client.ClientThread;
import com.Util.GeneralThreadPool;
import com.Util.StreamUtil;



public class ServerExecutor extends Thread {

	private ServerSocket _server;

	private int _port = 0;

	private static final Logger _log = Logger.getLogger(ServerExecutor.class.getName());


	private boolean _msg ;

	public ServerExecutor(final int port) {
		try {
			this._port = port;
			this._server = new ServerSocket(this._port);
		} catch (final SocketTimeoutException e) {
			_log.log(Level.SEVERE ,"連線超時:(" + this._port + ")", e);

		} catch (final IOException e) {
			_log.log(Level.SEVERE ,"IP位置加載錯誤 或 端口位置已被佔用:(" + this._port + ")", e);

		} finally {
			if(!_msg){
				_log.info("[D] " + this.getClass().getSimpleName() + " 開始監聽服務端口:(" + this._port + ")");
				_msg = true;
			}
		}
	}


	@Override
	public void run() {
		try {
			while (this._server !=null) {
				Socket socket = null;
				try {
					socket = this._server.accept();
					if (socket != null) {
						final String host = socket.getInetAddress().getHostAddress();
//						final boolean is_start = Config.PORT_LIST.get(_port);
						final boolean is_start = true;
						if(is_start){
							if(host.contains("192.168.1.100")){
								System.out.println("收到來自 :" + host+" : "+_port+" 的關閉命令。");
								Config.PORT_LIST.put(_port, false);
								StreamUtil.close(socket);
								Set<Integer> set = Config.PORT_LIST.keySet();
								boolean reStart = true;
								for(final int key : set){
									if(Config.PORT_LIST.get(key)){
										reStart = false;
										break;
									}
								}
								if(reStart){
//									Process process = Runtime.getRuntime().exec("shutdown /r /t 2");
//									try {
//										process.waitFor();
//									} catch (InterruptedException e) {
//										e.printStackTrace();
//									}
//									System.exit(0);
								}
							}else{
								System.out.println("嘗試連線的IP:" +host+":"+_port);
								if(_port == 6263){
									ClientThread ct = new ClientThread(socket , 43082);
									Config.CLIENT_THREAD.add(ct);
									GeneralThreadPool.getInstance().execute(ct);
								}else if (_port == 6262){
									ClientThread ct = new ClientThread(socket , 43081);
									Config.CLIENT_THREAD.add(ct);
									GeneralThreadPool.getInstance().execute(ct);
								}
							}
						}else{
							if(host.contains("192.168.1.100")){
								System.out.println("收到來自 :" + host+" : "+_port+" 的開啟命令。");
								System.out.println("監聽伺服器啟用中...!!!");
								Config.PORT_LIST.put(_port, true);
								StreamUtil.close(socket);
							}else{
								System.out.println("【未開啟】嘗試連線的IP " +" : "+_port+ host);
								StreamUtil.close(socket);
							}
						}
					}
				} catch (final SecurityException e) {
				}
			}
		} catch (final IOException e) {
			//			_log.log(Level.SEVERE , e.getLocalizedMessage() , e);
		} finally {
			final String lanInfo = "[D] " + this.getClass().getSimpleName() + " 服務器核心關閉監聽端口(" + this._port + ")";
			_log.info(lanInfo);
		}
	}
	/**
	 * 停止監聽
	 */
	public void stopEcho() {
		try {
			if (this._server != null) {
				StreamUtil.close(this._server);
				StreamUtil.interrupt(this);
				this._server = null;
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);

		} finally {

		}
	}


	/**
	 * 啟動監聽
	 * @throws IOException
	 */
	public void stsrtEcho() throws IOException {
		GeneralThreadPool.getInstance().execute(this);
	}



}
